import os
from sys import argv
from subprocess import check_output, CalledProcessError
from my_utils import Timer


class Shell(Timer):
    def __init__(self):
        super().__init__()
        self.user = ''

    def set_user(self, user, login=True):
        if user == 'root':
            self.user = 'sudo '
        else:
            if login:
                self.user = 'sudo -i -u %s ' % user
            else:
                self.user = 'sudo -u %s ' % user

    def sudo(self, cmd):
        return self.user + cmd

    def execute(self, cmd):
        """执行Linux命令"""
        cmd = self.sudo(cmd)
        if self.system == 'Linux':
            os.system(cmd)
        else:
            print(cmd)

    def evaluate(self, cmd):
        """执行Linux命令并返回结果，Python2返回str，Python3返回bytes"""
        cmd = self.sudo(cmd)
        if self.system == 'Linux':
            return check_output(cmd, shell=True).decode().strip()
        return cmd


class ParameterUtil(Shell):
    def __init__(self, **kwargs):
        super().__init__()
        self.parameters = kwargs
        # 从命令行获取参数
        for a in argv[1:]:
            k, v = a.split('=', 1)
            self.parameters[k.strip()] = v.strip()

    def cat_hdfs(self, file_path):
        """从HDFS读取配置文件，并获取参数"""
        cmd = 'hadoop fs -cat ' + file_path
        try:
            self._properties2dict(self.evaluate(cmd))
        except CalledProcessError:
            print('HDFS文件不存在')

    def read_local_file(self, file_path):
        """从本地读取配置文件，并获取参数"""
        try:
            with open(file_path) as f:
                self._properties2dict(f.read())
        except IOError:
            print('本地配置文件不存在')

    def _properties2dict(self, properties):
        """properties文件内容解析"""
        for r in properties.strip().split('\n'):
            if (not r.startswith('#')) and (r.find('=') > 0):
                k, v = r.split('=', 1)
                k, v = k.strip(), v.strip()
                self.parameters[k] = self.get(k, v)

    def get(self, key, default=None):
        """获取参数值"""
        return self.parameters.get(key, default)

    @property
    def ymd(self):
        """获取日期，格式YYYY-MM-DD，默认昨天"""
        return self.get('ymd', self.yesterday)
